var app = getApp();
Page({
  data: {
    list:[],
    count:0
  },
  onLoad: function (o) {
    wx.showLoading({title: '加载中',mask:true})
    this.getInit(o)
    wx.hideLoading()
  },
  getInit(o){
    var t = this;
    app.args.request({
      url:'https://live.gdkktz.cn/shuidi/goodlist',
      success(e){
        t.setData({list:t.reorder(e.data,2),count:o.c});
      }
    });
    app.args.request({
      url:'https://live.gdkktz.cn/shuidi/login',
      data:{
        storeId:app.args.api.siteinfo.acid,
      },
      success(e){
        console.log(e)
        t.setData({count:e.shuidicount})
      }
    });
  },
  // 重置数据顺序column-count
  reorder(arr, columns){
    const cols = columns;
    const out = [];
    let col = 0;
    while(col < cols) {
        for(let i = 0; i < arr.length; i += cols) {
            let _val = arr[i + col];
            if (_val !== undefined)
                out.push(_val);
        }
        col++;
    }
    return out;
  },
  getGood(e){
    var t = this, item = e.currentTarget.dataset.item
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    wx.request({
      url:'https://live.gdkktz.cn/shuidi/buy',
      data:{
        goodId:item.id,
        storeId:app.args.api.siteinfo.acid,
        access_token:wx.getStorageSync('ACCESS_TOKEN')
      },
      success(e){
        console.log('buy',e)
        wx.hideLoading()
        e = e.data;
        if(e.result < 0 ){
          wx.showToast({title:e.message,icon:'none'});
          return;
        }
        wx.showToast({title:'兑换成功',icon:'none'});
        let pages = getCurrentPages(),prevPage = pages[pages.length - 2];
        prevPage.setData({shuidicount:t.data.count-item.shuidi_count});
        t.setData({count:t.data.count-item.shuidi_count});
        setTimeout(wx.hideToast,1000);
      }
    });
  }
});